/*package com.lhfeiyu.action.front.auction;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.config.Const;
import com.lhfeiyu.service.AuctionQuickGoodsService;
import com.lhfeiyu.service.AuctionQuickService;
import com.lhfeiyu.service.AuthCheckService;
import com.lhfeiyu.service.base.ShopService;
import com.lhfeiyu.service.base.GoodsPictureService;
import com.lhfeiyu.service.base.UserFundService;
import com.lhfeiyu.service.base.UserService;
import com.lhfeiyu.tools.base.ActionUtil;
import com.lhfeiyu.tools.base.Check;
import com.lhfeiyu.tools.base.Result;
import com.lhfeiyu.util.base.RequestUtil;
import com.lhfeiyu.config.Page;
import com.lhfeiyu.po.AuctionQuick;
import com.lhfeiyu.po.AuctionQuickGoods;
import com.lhfeiyu.po.base.GoodsPicture;
import com.lhfeiyu.po.base.Shop;
import com.lhfeiyu.po.base.User;
import com.lhfeiyu.po.base.UserFund;

@Controller
public class AuctionQuickHallAction {
	@Autowired
	private AuctionQuickInstService aqiService;
	@Autowired
	private AuctionQuickService aqService;
	@Autowired
	private AuctionQuickGoodsService aqgService;
	@Autowired
	private GoodsPictureService gpService;
	@Autowired
	private AuthCheckService authCheckService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserFundService userFundService;
	@Autowired
	private ShopService shopService;
	
	private static Logger logger = Logger.getLogger("R");
	
	
	@RequestMapping(value="/auctionQuickHall")
	public ModelAndView auctionQuickHall(ModelMap modelMap,HttpServletRequest request
			,@RequestParam Integer typeId
			,@RequestParam(required=false) String r) {
		String path = Page.aqHall;
		try{
			modelMap = authCheckService.checkWxLogin(request, modelMap);
			
			User user = ActionUtil.checkSession4User(request.getSession());
			if(null == user){
				modelMap.put("jumpUrl", "/auctionQuickHall?r="+r);
				return new ModelAndView(Page.login,modelMap);
			}
			int userId = user.getId();
			Map<String,Object> map = new HashMap<String,Object>();
			
			map.put("userId", userId);
			map.put("ur_shop", 1);
			//creditMargin
			List<User> db_userList = userService.selectListByCondition(map);
			User db_user;
			if(Check.isNotNull(db_userList)){
				db_user = db_userList.get(0);
			}else{
				return null;
			}
			if(null == db_user.getPhone() || "".equals(db_user.getPhone())){
				modelMap.put("noPhone", "noPhone");//未绑定手机号码
			}
			map.clear();
			map.put("userId", userId);
			List<UserFund> userFundList = userFundService.selectListByCondition(map);
			if(userFundList.size() > 0){
				UserFund userFund = userFundList.get(0);
				modelMap.put("userFund", userFund);
				if(null == userFund.getPayPassword() || "".equals(userFund.getPayPassword())){
					modelMap.put("noPayPassword", "noPayPassword");//未设置支付密码
				}
			}
			List<Shop> shopList = shopService.selectListByCondition(map);
			if(null != shopList){
				if(shopList.size() > 0){
					modelMap.put("shop", shopList.get(0));
				}
			}
			map.clear();
			map = RequestUtil.getRequestParam(request);//自动获取所有参数（查询条件）
			map.put("notOver", 1);
			map.put("groupBy", "id");
			map.put("ascOrdesc", "ASC");
			List<AuctionQuick> auctionQuickList = aqService.selectListByCondition(map);
			Integer availableCount = aqService.selectCountByCondition(map);
			map.clear();
			map.put("status", 3);//3:已经成交的
			Integer doneCount = aqgService.selectCountByCondition(map);
			
			modelMap.put("availableCount", availableCount);
			modelMap.put("doneCount", doneCount);
			if(null != auctionQuickList && auctionQuickList.size()>0){
				modelMap.put("goods", goodsList.get(0));
				AuctionQuick aq = auctionQuickList.get(0);
				Integer hostId = aq.getUserId();
				if(null != hostId){//判断是否为主持人
					int hostUserId = hostId;
					if(hostUserId == userId){
						modelMap.put("host", 1);
					}
				}
				modelMap.put("aq", aq);
				BigDecimal bailBD = aq.getBail();
				Integer creditMoney = db_user.getCreditMargin();
				//信誉保证金:信誉保证金必须大于保证金
				if(null != bailBD && (null == creditMoney || bailBD.doubleValue() > creditMoney)){
					modelMap.put("creditMoneyLack", 1);//前台提示交纳的保证金不足
					modelMap.put("bail", bailBD.doubleValue());
					modelMap.put("creditMoney", creditMoney);
				}
				String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
				//String sig = ConstField.generateSubSig(user.getThirdName(),user.getThirdPassword(),timeStamp);
				String sig = Const.generateSubSig(user.getSerial(), timeStamp);//应用登陆
				modelMap.put("username", user.getUsername());
				modelMap.put("senderId", userId);
				modelMap.put("userTokenId", user.getThirdName());
				modelMap.put("userTokenPswd", user.getThirdPassword());
				modelMap.put("senderName", user.getUsername());
				modelMap.put("senderAvatar", user.getAvatar());
				modelMap.put("sig", sig);
				modelMap.put("timeStamp", timeStamp);
				modelMap.put("receiverId",receiver.getId());
				modelMap.put("receiverTokenId", receiver.getThirdName());
				modelMap.put("reveiverName", receiver.getUsername());
				modelMap.put("reveiverAvatar", receiver.getAvatar());
				
				modelMap.put("senderSerial", user.getSerial());//应用登陆对应的账号：用户序号
				
			}else{
				path = Page.auctionQuick;
				modelMap.put("status", "done");
			}
		}catch(Exception e){
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载即时拍拍卖大厅页面出现异常_"+e.getMessage());
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/aqgList/{auctionId}")
	public ModelAndView auctionQuickGoods(ModelMap modelMap,HttpServletRequest request,
			@PathVariable Integer auctionId, @RequestParam(required=false) String r) {
		String path = Page.aqGoods;
		try{
			modelMap = authCheckService.checkWxLogin(request, modelMap);
			
			User sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String url =  "/aqgList/"+auctionId;
				if(null != r)url += "?r="+r;
				return Result.userSessionInvalid(modelMap, url);
			}
			Map<String, Object> map = RequestUtil.getRequestParam(request);//自动获取所有参数（查询条件）
			map.put("auctionId", auctionId);//在URL路径中获取的参数不为被自动获取，需要手动存入paramMap
			List<AuctionQuick> auctionQuickList = aqService.selectListByCondition(map);
			List<AuctionQuickGoods> goodsList = aqgService.selectListByCondition(map);
			
			if(null != goodsList && goodsList.size()>0 && null != auctionQuickList && auctionQuickList.size()>0){
				modelMap.put("goodsList", goodsList);
				modelMap.put("aq", auctionQuickList.get(0));
				modelMap.put("auctionId", auctionId);
			}else{
				path = Page.auctionQuick;
				modelMap.put("status", "done");
			}
		}catch(Exception e){
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载即时拍拍卖-藏品展示页面出现异常_"+e.getMessage());
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/aqg/{goodsId}/{auctionId}")
	public ModelAndView auctionQuickGoodsDetail(ModelMap modelMap,HttpServletRequest request,
			@PathVariable Integer goodsId, @PathVariable Integer auctionId,@RequestParam(required=false) String r) {
		String path = Page.aqGoodsDetail;
		try{
			modelMap = authCheckService.checkWxLogin(request, modelMap);
			
			User sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String url =  "/aqg/"+goodsId+"/"+auctionId;
				if(null != r)url += "?r="+r;
				return Result.userSessionInvalid(modelMap, url);
			}
			Map<String, Object> map = RequestUtil.getRequestParam(request);//自动获取所有参数（查询条件）
			map.put("goodsId", goodsId);//在URL路径中获取的参数不为被自动获取，需要手动存入paramMap
			map.put("auctionId", auctionId);//在URL路径中获取的参数不为被自动获取，需要手动存入paramMap
			List<AuctionQuick> auctionQuickList = aqService.selectListByCondition(map);
			List<AuctionQuickGoods> goodsList = aqgService.selectListByCondition(map);
			List<GoodsPicture> picList = gpService.selectListByCondition(map);
			map.remove("goodsId");
			List<AuctionQuickGoods> allGoodsList = aqgService.selectListByCondition(map);
			if(null != goodsList && goodsList.size()>0 && null != auctionQuickList && auctionQuickList.size()>0){
				modelMap.put("goods", goodsList.get(0));
				modelMap.put("goodsList", allGoodsList);
				modelMap.put("picList", picList);
				modelMap.put("ap", auctionQuickList.get(0));
			}else{
				path = Page.auctionQuick;
				modelMap.put("status", "done");
			}
		}catch(Exception e){
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载即时拍拍卖-藏品详情页面出现异常_"+e.getMessage());
		}
		return new ModelAndView(path, modelMap);
	}
	
	@ResponseBody
	@RequestMapping(value="/getNextAuctionQuickGoods", method=RequestMethod.POST)
	public JSONObject getNextAuctionQuickGoods(HttpServletRequest request,@RequestParam Integer auctionId) {
		List<AuctionQuickGoods> AuctionQuickGoodsList = null;
		JSONObject json = new JSONObject();
		try {
			Map<String, Object> map = RequestUtil.getRequestParam(request);//自动获取所有参数（查询条件）
			AuctionQuick aq = aqService.selectByPrimaryKey(auctionId);
			Integer haveBegun = aq.getHaveBegun();
			if(null == haveBegun)haveBegun = 1;
			json.put("haveBegun", haveBegun);
			
			map.remove("lastAuctionQuickGoodsId");
			Integer total = aqgService.selectCountByCondition(map);
			map.put("status1", 1);//未进行拍卖的（仅剩XX件）
			Integer remain = aqgService.selectCountByCondition(map);
			map.put("status", 3);//成交的
			map.remove("status1");
			Integer deal = aqgService.selectCountByCondition(map);
			
			map.remove("status");
			map.put("status1",1);//未进行拍卖的
			map.put("start", 0);
			map.put("count", 1);
			map.put("orderBy", "id");
			map.put("ascOrdesc", "ASC");
			map.put("status1",1);//加载未拍卖的最近的一条
			AuctionQuickGoodsList = aqgService.selectListByCondition(map);
			if(null != AuctionQuickGoodsList && AuctionQuickGoodsList.size() > 0){
				AuctionQuickGoods a = AuctionQuickGoodsList.get(0);
				Date d = a.getRefreshTime();
				long remainSeconds = calculateRemainSeconds(d);
				if(null != d){
				}else{
					AuctionQuickGoods tempAG = new AuctionQuickGoods();
					tempAG.setId(a.getId());
					tempAG.setRefreshTime(new Date());
					aqgService.updateByPrimaryKeySelective(tempAG);
				}
				json.put("remainSeconds", remainSeconds);
				json.put("auctionQuickGoods", a);
				json.put("total", total);
				json.put("remain", remain);
				json.put("deal", deal);
				json.put("status", "success");
			}else{
				Date date = new Date();
				AuctionQuick new_aq = new AuctionQuick();
				new_aq.setId(auctionId);
				new_aq.setHaveBegun(3);
				new_aq.setEndTime(date);
				aqService.updateByPrimaryKeySelective(new_aq);//更新即时拍状态
				
				map.clear();
				map.put("notOver", 1);
				map.put("groupBy", "id");
				map.put("ascOrdesc", "ASC");
				List<AuctionQuick> auctionQuickList = aqService.selectListByCondition(map);
				if(null != auctionQuickList && auctionQuickList.size()>0){
					AuctionQuick firstAQ = auctionQuickList.get(0);
					new_aq.setId(firstAQ.getId());
					new_aq.setHaveBegun(1);
					new_aq.setEndTime(null);
					Calendar c = Calendar.getInstance();
					c.setTime(date);
					c.set(Calendar.MINUTE, c.get(Calendar.MINUTE)+2);
					new_aq.setStartTime(c.getTime());
					aqService.updateByPrimaryKeySelective(new_aq);//更新下一场的即时拍状态,开始时间
				}
				json.put("status", "over");
				json.put("msg", "拍卖已结束");
			}
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_加载即时拍拍品列表出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/updateAuctionQuickGoods", method=RequestMethod.POST)
	public JSONObject updateAuctionQuickGoods(@ModelAttribute AuctionQuickGoods AuctionQuickGoods,HttpServletRequest request,
			@RequestParam(required=false,value="done")Integer done){
		JSONObject json = new JSONObject();
		try {
			User user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			if(null == AuctionQuickGoods.getId()){
				json.put("status", "id_null");
				json.put("msg","该拍品已不存在");
				return Result.success(json);
			}
			AuctionQuickGoods ag = aqgService.selectByPrimaryKey(AuctionQuickGoods.getId());
			Integer status = ag.getMainStatus();
			if(null != status && 2 == status){
				json.put("status", "already_done");
				json.put("msg","该拍品已流拍");
				return Result.success(json);
			}else if(null != status && 3 == status){
				json.put("status", "already_deal");
				json.put("msg","该拍品已被其他会员拍下");
				return Result.success(json);
			}
			
			Date date = new Date();
			if(null != done){//成交,流拍
				Integer userId = ag.getOfferUserId();
				AuctionQuickGoods a = new AuctionQuickGoods();
				a.setId(ag.getId());
				if(null != userId){//已有人出价：成交
					a.setDealTime(date);
					a.setMainStatus(3);
					//通知购买人，和卖家
				}else{//没有人出价：流拍
					a.setMainStatus(2);
				}
				aqgService.updateByPrimaryKeySelective(a);
				json.put("status", "success");
				json.put("msg", "操作成功");
				return Result.success(json);
			}

			//出价
			AuctionQuickGoods.setUserId(null);
			AuctionQuickGoods.setAuctionId(null);
			AuctionQuickGoods.setGoodsId(null);
			AuctionQuickGoods.setGoodsSerial(null);
			AuctionQuickGoods.setPriceBegin(null);
			AuctionQuickGoods.setDeletedAt(null);
			AuctionQuickGoods.setDeletedBy(null);
			AuctionQuickGoods.setUpdatedAt(date);
			AuctionQuickGoods.setOfferUserId(user.getId());
			AuctionQuickGoods.setOfferUsername(user.getUsername());
			AuctionQuickGoods.setUpdatedBy(user.getUsername());
			AuctionQuickGoods.setRefreshTime(date);//倒计时的刷新时间
			aqgService.updateByPrimaryKeySelective(AuctionQuickGoods);
			long remainSeconds = calculateRemainSeconds(date);
			json.put("remainSeconds", remainSeconds);
			json.put("status", "success");
			json.put("msg", "操作成功");
		}catch (Exception e) {
			e.printStackTrace();
			json.put("msg", "操作失败");
			Result.catchError(e, logger, "LH_ERROR_修改即时拍拍品状态出现异常_", json);
		}
		return Result.success(json);
	}
	
	private long calculateRemainSeconds(Date d){
		long remainSeconds = 120;
		if(null != d){
			Calendar cNow = Calendar.getInstance();
			Calendar c = Calendar.getInstance();
			c.setTime(d);
			long millisecond = cNow.getTimeInMillis() - c.getTimeInMillis();
			long second = millisecond/1000;
			remainSeconds = 120 - second;
			//System.out.println(remainSeconds);
			if(remainSeconds < 0 || remainSeconds > 120){
				remainSeconds = 120;
			}
		}
		//System.out.println(remainSeconds);
		return remainSeconds;
	}
	
	@ResponseBody
	@RequestMapping(value="/getAQGRemainSeconds", method=RequestMethod.POST)
	public JSONObject getAQGRemainSeconds(HttpServletRequest request, @RequestParam Integer AuctionQuickGoodsId){
		JSONObject json = new JSONObject();
		try {
			User user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			AuctionQuickGoods aqg = aqgService.selectByPrimaryKey(AuctionQuickGoodsId);
			long remainSeconds = calculateRemainSeconds(aqg.getRefreshTime());
			json.put("status", "success");
			json.put("remainSeconds", remainSeconds);
		}catch (Exception e) {
			e.printStackTrace();
			json.put("msg", "操作失败");
			Result.catchError(e, logger, "LH_ERROR_加载最新倒计时出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/setAQGRemainSeconds", method=RequestMethod.POST)
	public JSONObject setAQGRemainSeconds(HttpServletRequest request, @RequestParam Integer auctionGoodsId){
		JSONObject json = new JSONObject();
		try {
			User user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			AuctionQuickGoods aqg = aqgService.selectByPrimaryKey(auctionGoodsId);
			Integer auctionId = aqg.getAuctionId();
			if(null != auctionId){
				AuctionQuick aq = aqService.selectByPrimaryKey(auctionId);
				int aqId = aq.getUserId();
				int userId = user.getId();
				if(aqId == userId){//只有该次拍卖的管理员才能修改
					Calendar now = Calendar.getInstance();
					now.add(Calendar.SECOND, -100);//最长时间是120秒，则剩余20秒
					AuctionQuickGoods newAqg = new AuctionQuickGoods();
					newAqg.setId(aqg.getId());
					newAqg.setRefreshTime(now.getTime());
					aqgService.updateByPrimaryKeySelective(newAqg);//更新倒计时
					json.put("remainSeconds", 20);
				}
			}
			json.put("status", "success");
		}catch (Exception e) {
			e.printStackTrace();
			json.put("msg", "操作失败");
			Result.catchError(e, logger, "LH_ERROR_开始倒计时出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getAuctionQuickHaveBegun", method=RequestMethod.POST)
	public JSONObject getAuctionQuickHaveBegun(HttpServletRequest request,
			@RequestParam Integer auctionId) {
		JSONObject json = new JSONObject();
		try {
			//Map<String, Object> map = ActionUtil.getAllParam(request);
			AuctionQuick aq = aqService.selectByPrimaryKey(auctionId);
			Integer haveBegun = aq.getHaveBegun();
			if(null == haveBegun)haveBegun = 1;
			json.put("haveBegun", haveBegun);
			json.put("status", "success");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_加载即时拍拍场开拍状态出现异常_", json);
		}
		return Result.success(json);
	}
	
}
*/